#!/usr/bin/env python
# coding=utf-8
'''
@Author: 以谁为师
@Website: attacker.club
@Date: 2020-07-23 11:24:26
LastEditTime: 2020-09-26 13:41:47
@Description: 

pip install aliyun-python-sdk-core  # SDK核心库
pip install aliyun-python-sdk-cms   # 云监控
执行: python redis_main.py 实例id 监控项目
'''
import time
import sys
import json

from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkcms.request.v20190101.DescribeMetricDataRequest import DescribeMetricDataRequest


class aliyun_monitor(object):
    def __init__(self, metric, instanceId):
        # 传入metric指标

        self.metric = metric
        self.instanceId = instanceId

    def query(self):
        request = DescribeMetricDataRequest()
        request.set_accept_format('json')
        # 采样周期为60s，Period赋值为60或60的整数倍。
        request.set_Period("60")
        # 命名空间
        request.set_Namespace("acs_kvstore")

        # 实例id
        request.set_Dimensions(
            {'instanceId': self.instanceId}
        )
        # 监控项
        request.set_MetricName(self.metric)

        # response
        response = client.do_action_with_exception(request)
        # print(str(response, encoding='utf-8'))

        # json结果处理
        datadict = json.loads(response)
        print(datadict)
        res_str = datadict['Datapoints']
        data = eval(res_str)
        print(data)
        print(int(data[-1]['Maximum']))


if __name__ == '__main__':

    client = AcsClient('LTAI4G3b8aqwJiKtiRLaDxu4',
                           'lzhBwAqbUVsyQtYddwOxqhifJwe5QS', 'me-east-1')
        # client = AcsClient('LTAI4GA4QAJwsytYtn94Mgwc',
        #                    'eEOpCGoE1Ou7SiJpxz1Vqx3gxLfr2i', 'cn-hangzhou')

    instanceId = "r-tc5hesxlqmzk7nvmk8"
    Monitor = aliyun_monitor("SplitrwHitRate", instanceId)
    Monitor.query()

    